<?php
require_once ('database.php');

class GeneralDatabase {

	protected static $table_name;
	protected static $db_fields = new array();

	public static function set_table_name($table_name){
		self::table_name = $table_name;
	}
	
	public static function set_db_fields($db_fields){
		self::db_fields = $db_fields;
	}

	/**
	 * GeneralDatabase::find_by_sql()
	 * 
	 * @param string $sql
	 * @return
	 */
	public static function find_by_sql($sql = "")
	{
		global $database;
		$result_set = $database->query($sql);
		$object_array = array();
		while ($row = $database->fetch_array($result_set))
		{
			$object_array[] = self::instantiate($row);
		}
		return $object_array;
	}

	/**
	 * GeneralDatabase::instantiate()
	 * 
	 * @param mixed $record
	 * @return
	 */
	private  static function instantiate($record)
	{
		// Could check that $record exists and is an array
		$object = new self;

		foreach ($record as $attribute => $value)
		{
			if ($object->has_attribute($attribute))
			{
				$object->$attribute = $value;
			}
		}
		return $object;
	}

	private function has_attribute($attribute)
	{
		// We don't care about the value, we just want to know if the key exists
		// Will return true or false
		return array_key_exists($attribute, $this->attributes());
	}

	protected function sanitized_attributes()
	{
		global $database;
		$clean_attributes = array();
		// sanitize the values before submitting
		// Note: does not alter the actual value of each attribute
		foreach ($this->attributes() as $key => $value)
		{
			$clean_attributes[$key] = $database->escape_value($value);
		}
		return $clean_attributes;
	}


	protected function attributes()
	{
		// return an array of attribute names and their values
		$attributes = array();
		foreach (self::$db_fields as $field)
		{
			if (property_exists($this, $field))
			{
				$attributes[$field] = $this->$field;
			}
		}
		return $attributes;
	}


}